import pymongo
import re
from pyquery import PyQuery as pq
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from taobao.config_taobao import *

client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

browser = webdriver.PhantomJS(executable_path=r"D:\Program Files (x86)\phantomjs\bin\phantomjs.exe", service_args=SERVICE_ARGS)
wait = WebDriverWait(browser, 10)

# 需要为phantomjs设置窗口大小
browser.set_window_size(1400, 900)

def search():
    print("正在搜索")
    try:
        browser.get("https://www.taobao.com")
        input = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#q'))
        )
        submit = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button'))
        )
        input.send_keys(KEY_WORD)
        submit.click()

        # 对第一页进行解析，所以后续要从第二页开始
        get_products()

        total = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total'))
        )

        return total.text
    except TimeoutException:
        return search()

def next_page(page_number):
    print("正在翻页", page_number)
    try:
        input = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > input'))
        )
        submit = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit'))
        )
        input.clear()
        input.send_keys(page_number)
        submit.click()

        # 比较输入页码框和高亮部分的内容是否相同
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > ul > li.item.active > span'), str(page_number))
        )
        get_products()
    except TimeoutException:
        next_page(page_number)

def get_products():
    wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .items .item'))
    )
    html = browser.page_source
    doc = pq(html)
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product = {
            'image': item.find('.pic .img').attr('src'),
            'price': item.find('.price').text(), # 获取标签内的文字
            'deal': item.find('.deal-cnt').text()[:-3],
            'title': item.find('.title').text(),
            'shop': item.find('.shop').text(),
            'location': item.find('.location').text()
        }
        print(product)
        # 获取到商品的字典形式的数据结构后，存储到mongodb中
        save_to_mongo(product)

def save_to_mongo(result):
    try:
        if db[MONGO_TABLE].insert(result):
            print('存储到MONGODB成功', result)
    except Exception:
        print('存储失败', result)

def main():
    # search()
    try:
        # 在获取总页数的时候，已经加载了第一页，获取了第一页的宝贝数据
        total = search()
        total = int(re.compile('(\d+)').search(total).group(1))
        print(total)
        # 这里的循环就要从第二页开始
        for i in range(2, total + 1):
            next_page(i)
    except Exception:
        print("出错啦")
    finally:
        browser.close()

if __name__ == '__main__':
    main()
